using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using FixedHeaderSample.WebSocketServer.Commands;
using FixedHeaderSample.WebSocketServer.Server;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SuperSocket;
using SuperSocket.Command;
using SuperSocket.WebSocket.Server;

namespace FixedHeaderSample.WebSocketServer
{
    class Program
    {
        static async Task Main()
        {
            var host = WebSocketHostBuilder.Create()
                //注册WebSocket消息处理器(使用UseCommand注册命令之后该处理器不起作用)
                .UseWebSocketMessageHandler(async (session, package) =>
                {
                    Console.WriteLine($@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Receive message: {package.Message}.");

                    //Send message back
                    var message =
                        $@"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Hello from WebSocket Server: {package.Message}.";
                    await session.SendAsync(message);
                })
                .UseCommand<MyPackageInfo, MyPackageConverter>(commandOptions =>
                {
                    //注册命令
                    commandOptions.AddCommand<MyCommand>();
                })
                .UseSession<MyWebSocketSession>()
                .UseInProcSessionContainer()
                .UseMiddleware<MyMiddleware>()
                .ConfigureAppConfiguration((hostCtx, configApp) =>
                {
                    configApp.AddInMemoryCollection(new Dictionary<string, string>
                    {
                        {"serverOptions:name", "TestServer"},
                        {"serverOptions:listeners:0:ip", "Any"},
                        {"serverOptions:listeners:0:port", "4041"}
                    });
                })
                .ConfigureLogging((hostCtx, loggingBuilder) =>
                {
                    //添加控制台输出
                    loggingBuilder.AddConsole();
                })
                .Build();
            await host.RunAsync();
        }
    }
}
